// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2

package main

import (
	"flag"
	"fmt"
	"net/http"
	"zero_study/common/response"

	"github.com/zeromicro/go-zero/rest/httpx"

	"zero_study/user/api_jwt/internal/config"
	"zero_study/user/api_jwt/internal/handler"
	"zero_study/user/api_jwt/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/users.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	// 创建服务器时注册JWT验证失败的回调函数
	// 使用rest.WithUnauthorizedCallback选项将JwtUnauthorizedResult函数注册为JWT验证失败的回调处理函数
	server := rest.MustNewServer(c.RestConf, rest.WithUnauthorizedCallback(JwtUnauthorizedResult))
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}

// JwtUnauthorizedResult jwt验证失败的回调
// 当JWT验证失败时（如token缺失、过期、无效等），该函数会被调用
// 参数说明:
// w: HTTP响应写入器，用于向客户端写入响应数据
// r: HTTP请求对象，包含请求信息
// err: JWT验证失败的具体错误信息
func JwtUnauthorizedResult(w http.ResponseWriter, r *http.Request, err error) {
	fmt.Println("JWT验证失败:", err) // 输出具体的错误信息，便于调试
	// 返回自定义的错误响应格式
	httpx.WriteJson(w, http.StatusOK, response.Body{
		Code: 10087,  // 自定义错误码
		Msg:  "鉴权失败", // 错误消息
		Data: nil,    // 错误时数据为空
	})
}
